;
(function (window, angular) {
    'use strict';
    angular.module("Controller.Sales.SalesOrder", [])
        .controller("SalesOrderCtrl", ["$scope", "$state", "ybWidget", "ybHttp", "MESG_TYPE", "$timeout", "EventBus", "$filter", "UserContextService", "$stateParams", function ($scope, $state, ybWidget, ybHttp, MESG_TYPE, $timeout, EventBus, $filter, UserContextService, $stateParams) {
            $scope.activeFlag = [true, false, false];
            $scope.detailFlag = [true, true];
            $scope.datePickerFlag = [false, false];
            $scope.markInfo = {
                allCheckedBill: false,
                allCheckedMaterial: false,
                curRow: -1
            };

            $scope.claimOrderNo = '';
            $scope.borrowId = "";
            $scope.submitted = false;
            $scope.pageInfo = {
                totalPages: 1,
                totalRows: 0,
                pageSize: 10,
                curPage: 1
            };
            $scope.condition = {};
            $scope.toolbarConfig = {
                showAdvanceSearch: false,
                showColConfig: false,
                showMateriel: false
            };
            $scope.dataList = [];
            $scope.machineNoList = [];
            $scope.modelList = [];
            $scope.deliveryWayList = [];
            $scope.detailInfo = {
                crucialDevice: 0,
                entranceDevice: 0
            };
            var giveQuotaTypeEnum = {
                Ordinary: 1,
                Maintain: 2
            };

            $scope.submitEnum = {
                Save: 0,
                Submit: 1
            };

            $scope.costPriceShow = false;

            $scope.tabFlag = {};

            var tabFlag = {
                0: "详情",
                1: "新增",
                2: "编辑"
            };
            $scope.billTypeEnum = {
                Ordinary: 1,
                ThreePack: 2,
                Give: 3
            };
            var billTypeMapList = [
                {1: "普通"},
                {2: "三包"},
                {3: "赠送"},
                {4: "其他"}
            ];

            // 赠送额度类型枚举(数据字典中该字段和后台数据库中定义的字段枚举不一致，数据字典1:通用，2保养，库中是0：通用，1保养)
            $scope.giveQuotaTypeEnum = {
                Ordinary: 1,
                Maintain: 2,
            };

            var giveQuotaTypeMapList = [
                {1: "通用"},
                {2: "保养"}
            ];

            $scope.exportParam = {
                sectionUrl: ybHttp.RequestUrl("device", "/salesBill/export"),
                sectionParam: {ids: []},
                allUrl: ybHttp.RequestUrl("device", "/salesBill/exportAll")
            };
            $scope.orderObj = {
                billType: $scope.billTypeEnum.Ordinary,
                billTypeStr: '普通',
                detailVOList: []
            };
            $scope.isSap = 0;
            // $scope.purchaseLevelList = [];
            $scope.tableConfig = {
                fixedWidth: 150,
                scrollWidth: 1400,
                tableCol: [
                    {
                        type: "",
                        name: "销售单号",
                        dataField: "salesBillNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "CRM单号",
                        dataField: "crmOrder",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "借用单号",
                        dataField: "borrowBillNo",
                        width: 180,
                        isShow: true,
                        isFixed: false,
                        clickFn: "viewDetail",
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "客户名称",
                        dataField: "clientName",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        name: "是否竞品客户",
                        dataField: "isCompetingDealerShow",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                    },
                    {
                        type: "",
                        name: "销售人员",
                        dataField: "servicePersonName",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单类型",
                        dataField: "billTypeStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "申请日期",
                        dataField: "createDateStr",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "收货人",
                        dataField: "consignee",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "联系方式",
                        dataField: "contactPhone",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "收货地址",
                        dataField: "receiptAddress",
                        width: 130,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "机型",
                        dataField: "model",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "使用整机编号",
                        dataField: "useMachineNo",
                        width: 100,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "结算整机编号",
                        dataField: "settleMachineNo",
                        width: 120,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "原因",
                        dataField: "reason",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "派工单号",
                        dataField: "workOrderNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "索赔单号",
                        dataField: "claimOrderNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "赠送额度类型",
                        dataField: "giveQuotaTypeStr",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "备注",
                        dataField: "remark",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "订单总价",
                        dataField: "totalOrderPrice",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "调整后总价",
                        dataField: "adjustedTotalPrice",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "创建出库单状态",
                        dataField: "createOutboundStatusStr",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库状态",
                        dataField: "outboundStatusStr",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "出库时间",
                        dataField: "outboundDateStr",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "",
                        name: "服务单号",
                        dataField: "serviceNo",
                        width: 150,
                        isShow: true,
                        isFixed: false,
                        toSort: true,
                        sortType: ""
                    },
                    {
                        type: "operate",
                        name: "操作",
                        dataField: "",
                        width: 110,
                        isShow: true,
                        isFixed: true,
                        toSort: false,
                        sortType: ""
                    }
                ]
            };

            $scope.materielTableConfig = {
                scrollWidth: 1910,
                tableCol: [
                    {
                        name: "零件编号",
                        width: 150,
                        dataField: "materialNo",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "零件中文名",
                        width: 200,
                        dataField: "materialDes",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "单位",
                        width: 80,
                        dataField: "unit",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "申请数量",
                        width: 80,
                        dataField: "applyQty",
                        input: true,
                        inputType: "num"
                    },
                    {
                        name: "单价",
                        width: 100,
                        dataField: "singlePrice",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "申请总价",
                        width: 100,
                        dataField: "applyTotalPrice",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "价格方案",
                        width: 140,
                        dataField: "priceGroup",
                        input: true,
                        inputType: "func"
                    },
                    {
                        name: "调整后单价",
                        width: 130,
                        dataField: "adjustedSinglePrice",
                        input: true,
                        inputType: "price"
                    },
                    {
                        name: "调整后总价",
                        width: 130,
                        dataField: "adjustedTotalPrice",
                        input: false,
                        inputType: ""
                    },
                    {
                        name: "创建出库单数量",
                        width: 130,
                        dataField: "createOutboundQty",
                        input: true,
                        inputType: ""
                    },
                    {
                        name: "实际出库数量",
                        width: 130,
                        dataField: "actualOutboundQty",
                        input: false,
                        inputType: ""
                    },
                    {
                        type: "cost",
                        name: "成本单价",
                        width: 100,
                        dataField: "costPrice",
                        input: false,
                        inputType: ""
                    },
                    {
                        type: "cost",
                        name: "成本小计",
                        width: 100,
                        dataField: "costSubtotal",
                        input: false,
                        inputType: ""
                    },
                ]
            };

            var btnPermissionCode = {
                salesOrderAdd: window.ActionCode.salesOrderAdd,
                salesOrderEdit: window.ActionCode.salesOrderEdit,
                salesOrderDel: window.ActionCode.salesOrderDel,
                salesOrderExport: window.ActionCode.salesOrderExport,
                showCostPrice: window.ActionCode.showCostPrice,
            };

            $scope.btnPermission = {
                salesOrderAdd: true,
                salesOrderEdit: true,
                salesOrderDel: true,
                salesOrderExport: true,
                showCostPrice: true
            };

            function setBtnPermission() {
                for (var key in btnPermissionCode) {
                    $scope.btnPermission[key] = UserContextService.CheckPermission([btnPermissionCode[key]]);
                }
            }

            $scope.setFixedWidth = function () {
                $scope.tbStyle = {
                    billFixedWidth: {left: $scope.tableConfig.fixedWidth + "px"}
                };
            };

            $scope.switchDataPicker = function (index) {
                $scope.datePickerFlag = [false, false];
                if (angular.isDefined(index)) {
                    $scope.datePickerFlag[index] = true;
                }
            };

            $scope.checkDate = function (obj, startFiled, endFiled) {
                var timeFormatObj = ybWidget.CheckDate(obj[startFiled], obj[endFiled]);
                if (!!timeFormatObj.tStart) {
                    obj[startFiled] = timeFormatObj.tStart;
                }
                if (!!timeFormatObj.tEnd) {
                    obj[endFiled] = timeFormatObj.tEnd;
                }
            };

            $scope.changeTab = function (index) {
                $scope.activeFlag = [false, false, false];
                $scope.activeFlag[index] = true;
                $scope.submitted = false;
                switch (index) {
                    case 0:
                        initData();
                        getDataList();
                        $scope.submitted = false;
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    default:
                        break;
                }
            };


            function initData() {
                $scope.tabFlag = {};
                $scope.detailInfo = {
                    crucialDevice: 0,
                    entranceDevice: 0
                };
                $scope.orderObj = {
                    headerInfo: {},
                    detailVOList: []
                };
                $scope.isSap = 0;
                $scope.markInfo.allCheckedMaterial = false;
                $scope.toolbarConfig.showMateriel = false;
                $scope.detailFlag = [true, true];
            }

            function getDataList(curPage) {
                $scope.markInfo = {
                    allCheckedBill: false,
                    allCheckedMaterial: false,
                    curRow: -1
                };
                $scope.exportParam.sectionParam.ids = [];
                var service = "device";
                var reqUrl = "/salesBill/list";
                var param = {};
                param.pageSize = $scope.pageInfo.pageSize;
                if (!!curPage) {
                    $scope.pageInfo.curPage = curPage;
                }
                param.pageNum = $scope.pageInfo.curPage;
                param.filters = $scope.condition;
                // param.filters.seller = true;
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    angular.forEach(resp.value.list, function (item) {
                        item.isChecked = false;
                        item.createDateStr = $filter("YbDate")(item.createDate, 'yyyy-MM-dd HH:mm:ss');
                        item.billTypeStr = $filter("BillTypeStatus")(item.billType);
                        item.giveQuotaTypeStr = $filter("GiveQuotaTypeStatus")(item.giveQuotaType);
                        item.createOutboundStatusStr = $filter("CreateOutboundStatus")(item.createOutboundStatus);
                        item.outboundStatusStr = $filter("OutboundStatus")(item.outboundStatus);
                        item.outboundDateStr = $filter("YbDate")(item.outboundDate, 'yyyy-MM-dd HH:mm:ss');
                        item.isCompetingDealerShow = $filter("TrueOrFalseOrNull")(item.isCompetingDealer);
                    });
                    $scope.pageInfo.totalRows = resp.value.total;
                    $scope.pageInfo.totalPages = resp.value.pages;
                    $scope.dataList = resp.value.list;
                    return resp.value.list;
                });
            }

            $scope.tdClick = function (item, fnType) {
                switch (fnType) {
                    case "viewDetail":
                        viewDetail(item);
                        break;
                    default:
                        break;
                }
            };


            $scope.toSort = function (config, index) {
                ybWidget.ToSort(config, index);
            };

            $scope.switchToolbar = function (toolbar) {
                if (!!$scope.toolbarConfig["show" + toolbar]) {
                    $scope.toolbarConfig["show" + toolbar] = false;
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig["show" + toolbar] = true;
                    });
                }
            };

            $scope.selectRow = function (index) {
                $scope.markInfo.cueRow = index
            };

            $scope.search = function (curpage) {
                getDataList(curpage);
            };

            $scope.reset = function () {
                $scope.condition = {seller: true};
            };

            $scope.switchDetailBar = function (index) {
                $scope.detailFlag[index] = !$scope.detailFlag[index];
            };


            $scope.delMateriel = function (item, index) {
                ybWidget.ShowMessage("确定要删除该记录吗？", MESG_TYPE.Ask).then(function () {
                    $scope.orderObj.detailVOList.splice(index, 1);
                    setTotalPrice();
                    setTotalPriceAdjust();
                    EventBus.Publish("setMaterial", item.materialsNo);
                });
            };

            $scope.batchDelMateriel = function () {
                var selectedCount = 0;
                for (var i = 0, len = $scope.orderObj.detailVOList.length; i < len; i++) {
                    if (!!$scope.orderObj.detailVOList[i].isChecked) {
                        selectedCount++;
                    }
                }
                if (!selectedCount) {
                    ybWidget.ShowMessage('请选择需要删除的行');
                    return;
                }
                ybWidget.ShowMessage("确定要删除选中的记录吗？", MESG_TYPE.Ask).then(function () {
                    for (var i = $scope.orderObj.detailVOList.length - 1; i >= 0; i--) {
                        if (!!$scope.orderObj.detailVOList[i].isChecked) {
                            $scope.orderObj.detailVOList.splice(i, 1);
                        }
                    }
                    if ($scope.orderObj.detailVOList.length === 0) {
                        $scope.markInfo.allCheckedMaterial = false;
                    }
                    setTotalPrice();
                    setTotalPriceAdjust();
                    EventBus.Publish("setMaterial");
                });
            };

            $scope.countTotal = function (item) {
                item.qtyErr = false;
                if (!item.purchaseQty || parseFloat(item.purchaseQty) <= 0) {
                    item.qtyErr = true;
                }
                item.totalPrice = $filter("decimalCover")(ybWidget.Times(item.purchaseQty, item.price), 2);
            };
            $scope.batchDel = function () {
                var deleteList = [];
                angular.forEach($scope.dataList, function (item) {
                    if (item.isChecked) {
                        deleteList.push(item.id);
                    }
                });
                if (deleteList.length === 0) {
                    ybWidget.ShowMessage('请选择可删除数据', MESG_TYPE.Error);
                    return;
                }
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function (data) {
                    var service = "device";
                    var reqUrl = "/salesBill/delete";
                    ybHttp.Post(service, reqUrl, deleteList).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };
            $scope.delApply = function (id) {
                ybWidget.ShowMessage("确定要删除吗？", MESG_TYPE.Ask).then(function () {
                    var service = "device";
                    var reqUrl = "/salesBill/delete";
                    ybHttp.Post(service, reqUrl, [id]).then(function (resp) {
                        if (resp.code !== 0) {
                            ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                            return;
                        }
                        ybWidget.ShowToaster('success', '操作成功');
                        getDataList();
                    });
                })
            };

            $scope.addApply = function () {
                $scope.tabFlag.type = 1;
                $scope.tabFlag.name = tabFlag[1];
                //dealerOrgId = "";

                // 新增时默认订单类型是普通
                $scope.orderObj.billType = $scope.billTypeEnum.Ordinary;
                if ($scope.isSWY) {
                    // 施维英新增时默认订单类型是赠送
                    $scope.orderObj.billType = $scope.billTypeEnum.Give;
                }
                angular.forEach(billTypeMapList, function (item) {
                    if (item.hasOwnProperty($scope.orderObj.billType)) {
                        $scope.orderObj.billTypeStr = item[$scope.orderObj.billType];
                    }
                });
                // 新增时默认赠送额度类型为通用
                $scope.orderObj.giveQuotaType = $scope.giveQuotaTypeEnum.Ordinary;
                setGiveQuotaType();

                $scope.orderObj.borrowBillNo = "";
                $scope.changeTab(2);
            };


            function getDetail(item) {
                var param = {
                    id: item.id
                };
                return ybHttp.Get('device', '/salesBill/detail', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    setMaterialDesc();
                    return resp.value;
                });
            }

            $scope.checkDate = function (item, start, end) {
                if ((angular.isUndefined(item[start]) || !item[start]) && (angular.isUndefined(item[end]) || !item[end])) {
                    return;
                }
                if (!!item[start] && (angular.isUndefined(item[end]) || !item[end])) {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    return;
                }
                if ((angular.isUndefined(item[start]) || !item[start]) && !!item[end]) {
                    item[end] = ybWidget.FormatEndDate(item[end]);
                    return;
                }
                var tmpTime = item[start];
                if (item[end] < item[start]) {
                    item[start] = ybWidget.FormatStartDate(item[end]);
                    item[end] = ybWidget.FormatEndDate(tmpTime);
                } else {
                    item[start] = ybWidget.FormatStartDate(item[start]);
                    item[end] = ybWidget.FormatEndDate(item[end]);
                }
            };

            // 设置赠送额度类型的值
            var setGiveQuotaType = function () {
                if ($scope.orderObj.giveQuotaType !== "" && $scope.orderObj.giveQuotaType !== null && $scope.orderObj.giveQuotaType !== undefined) {
                    angular.forEach(giveQuotaTypeMapList, function (item) {
                        if (item.hasOwnProperty($scope.orderObj.giveQuotaType)) {
                            $scope.orderObj.giveQuotaTypeStr = item[$scope.orderObj.giveQuotaType];
                        }
                    });
                }
            }

            $scope.editApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }
                    $scope.tabFlag.type = 2;
                    $scope.tabFlag.name = tabFlag[2];
                    $scope.orderObj = data.salesBillVO;
                    //获取整机编号列表
                    getMachineNoList();
                    if (!!$scope.orderObj.settleMachineNo) {
                        $scope.orderObj.settleMachineNo = {
                            name: $scope.orderObj.settleMachineNo,
                            code: $scope.orderObj.settleMachineNo
                        };
                    }
                    // 编辑时设置赠送额度类型初始值
                    setGiveQuotaType();
                    // 编辑时给使用整机编号赋值
                    $scope.orderObj.useMachineNo = {
                        name: $scope.orderObj.useMachineNo, code: $scope.orderObj.useMachineNo
                    };
                    // 根据客户名称和使用整机编号，查询机型列表
                    getModelList().then(function () {
                        $scope.orderObj.model = {code: data.salesBillVO.model, name: data.salesBillVO.model};
                    });


                    angular.forEach(data.materialList, function (item) {
                        item.materialsNo = item.materialsNo ? item.materialsNo : item.materialNo;
                    });

                    angular.forEach(billTypeMapList, function (item) {
                        if (item.hasOwnProperty($scope.orderObj.billType)) {
                            $scope.orderObj.billTypeStr = item[$scope.orderObj.billType];
                        }
                    });

                    $scope.orderObj.detailVOList = data.materialList;
                    $scope.orderObj.id = item.id;
                    $scope.changeTab(2);
                }).then(function () {
                    getPersonVehicleInfo();
                });
            };

            // 因新增时剩余赠送额度是选择客户时带过来的，所以编辑时需要重新根据客户来获取相关信息
            function getPersonVehicleInfo() {
                var param = {
                    clientName: $scope.orderObj.clientName,
                    carNo: $scope.orderObj.useMachineNo.name
                };
                ybHttp.Get('device', '/dealerVehicle/getPersonVehicleInfo', param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.orderObj.maintenanceLaveAmount = resp.value.maintenanceLaveAmount;
                    $scope.orderObj.maintenanceSendAmount = resp.value.maintenanceSendAmount;
                    $scope.orderObj.maintenanceUseAmount = resp.value.maintenanceUseAmount;
                    $scope.orderObj.universalLaveAmount = resp.value.universalLaveAmount;
                    $scope.orderObj.universalSendAmount = resp.value.universalSendAmount;
                    $scope.orderObj.universalUseAmount = resp.value.universalUseAmount;

                    return resp.value;
                });
            }


            function viewDetail(item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }

                    $scope.orderObj = data.salesBillVO;
                    setGiveQuotaType();
                    $scope.orderObj.detailVOList = data.materialList;
                    $scope.orderObj.billTypeStr = $filter("BillTypeStatus")($scope.orderObj.billType);

                    $scope.changeTab(3);
                });
            }

            $scope.auditApply = function (item) {
                getDetail(item).then(function (data) {
                    if (!data) {
                        return;
                    }

                    $scope.orderObj = data;
                    $scope.changeTab(1);
                });
            };


            $scope.selMateriel = function (e) {
                if (!!$scope.toolbarConfig.showMateriel) {
                    e.stopPropagation();
                } else {
                    $timeout(function () {
                        $scope.toolbarConfig.showMateriel = true;
                        EventBus.Publish("getMaterial");
                    });
                }
            };

            $scope.importMateriel = function () {
                var param = {
                    name: "零件",
                    templateReqService: "device",
                    templateReqUrl: "/salesBill/download",
                    importReqService: "device",
                    importReqUrl: "/salesBill/import",
                    importErrorUrl: ""
                };
                ybWidget.ImportFile(param).then(function (data) {
                    angular.forEach(data, function (item) {
                        item.isChecked = false;
                    });
                    $scope.orderObj.detailVOList = [];
                    $scope.orderObj.detailVOList = angular.copy(data);
                    angular.forEach($scope.orderObj.detailVOList, function (item) {
                        item.materialNo = item.materialsNo ? item.materialsNo : item.materialNo;
                        item.materialDes = item.materialsDesc;
                        item.applyQty = item.purchaseQty;
                        item.singlePrice = item.price;
                        item.applyTotalPrice = item.totalPrice;
                        item.adjustedSinglePrice = item.price;
                        item.adjustedTotalPrice = item.totalPrice;
                    });
                    setTotalPrice();
                    setTotalPriceAdjust();
                });
            };

            // 选中的零件变化后的回调
            $scope.$watch('orderObj.detailVOList.length', function () {
                setMaterialDesc();
            });

            function setMaterialDesc() {
                angular.forEach($scope.orderObj.detailVOList, function (item) {
                    item.materialNo = item.materialsNo ? item.materialsNo : item.materialNo;
                    item.materialDes = item.materialsDes ? item.materialsDes : item.materialDes;
                    item.singlePrice = item.price ? item.price : item.singlePrice; //单价
                    item.adjustedTotalPrice = item.totalPriceAfterAdjust ? item.totalPriceAfterAdjust : item.adjustedTotalPrice; // 调整后总价
                    item.adjustedSinglePrice = item.adjustedSinglePrice || item.adjustedSinglePrice==0 ? item.adjustedSinglePrice : item.singlePrice;
                });
            }

            $scope.saveData = function (type, invalid, statues) {
                if (!invalid) {
                    $scope.submitted = true;
                    return;
                }
                var listValid = true;
                var service = "device";
                var reqUrl = "/salesBill/add";

                if ($scope.tabFlag.type === 2) {
                    reqUrl = "/salesBill/update";
                }

                for (var i = 0, len = $scope.orderObj.detailVOList.length; i < len; i++) {
                    $scope.orderObj.detailVOList[i].qtyErr = false;
                    if (!$scope.orderObj.detailVOList[i].applyQty || parseFloat($scope.orderObj.detailVOList[i].applyQty) <= 0) {
                        $scope.orderObj.detailVOList[i].qtyErr = true;
                        listValid = false;
                        break;
                    }
                }
                if (!listValid) {
                    return;
                }
                if ($scope.orderObj.detailVOList.length === 0) {
                    ybWidget.ShowMessage("零件不可为空", MESG_TYPE.Error);
                    return;
                }

                // 新增时：如果订单类型为不为赠送---->将赠送类型置空
                // 修改时：------------------------>不操作赠送类型
                if ($scope.tabFlag.type !== 2 && $scope.orderObj.billType.toString() !== "3") {
                    $scope.orderObj.giveQuotaType = "";
                    $scope.orderObj.giveQuotaTypeStr = "";
                }

                // setMaterialDesc();
                var param = angular.copy($scope.orderObj);


                if (!!param.settleMachineNo) {
                    param.settleMachineNo = param.settleMachineNo.code ? param.settleMachineNo.code : param.settleMachineNo;
                } else {
                    param.settleMachineNo =  param.useMachineNo.code ? param.useMachineNo.code : param.useMachineNo;
                }

                param.status = statues;
                param.useMachineNo = param.useMachineNo.code;
                param.model = param.model.code;


                ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    ybWidget.ShowToaster('success', '操作成功');
                    $scope.changeTab(0);
                    if (type === "submit") {
                        ybWidget.ShowMessage("提交成功，是否立即创建销售出库单？", MESG_TYPE.Ask).then(function () {
                            $state.go("app.sales.salesOrderOut", {billId: resp.value})
                        })
                    }
                });
            };

            $scope.cancel = function () {
                $scope.changeTab(0);
            };

             //选择服务人员
             $scope.selectServicer = function () {
                var param = {
                    name: "销售人员",
                    type: 'servicer',
                    supplierOrgId: $scope.curOrgId,
                    roleName: ""
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.servicePersonId = data.userId;
                    $scope.orderObj.servicePersonName = data.name;
                });
            };

            // 新增编辑页面选择客户
            $scope.selectDealer = function () {
                var param = {
                    name: "客户",
                    type: "customer"
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.clientName = data.clientName;
                    $scope.orderObj.useMachineNo = {name: data.carNo, code: data.carNo};
                    $scope.orderObj.maintenanceLaveAmount = data.maintenanceLaveAmount;
                    $scope.orderObj.maintenanceSendAmount = data.maintenanceSendAmount;
                    $scope.orderObj.maintenanceUseAmount = data.maintenanceUseAmount;
                    $scope.orderObj.universalLaveAmount = data.universalLaveAmount;
                    $scope.orderObj.universalSendAmount = data.universalSendAmount;
                    $scope.orderObj.universalUseAmount = data.universalUseAmount;
                    $scope.orderObj.clientId = data.dealerOrgId;
                    // 选择完客户后，改变剩余赠送额度
                    $scope.getRemainingCredit(data);
                    // 选择完客户后，查询出结整机编号的列表
                    getMachineNoList();
                    // 选择完客户后$scope.orderObj.useMachineNo会变成｛name:"",code:""｝的形式
                    // 选择完客户，默认结算整机编号为使用整机编号
                    if ((typeof $scope.orderObj.useMachineNo) !== "string") {
                        $scope.orderObj.settleMachineNo = $scope.orderObj.useMachineNo;
                    } else {
                        $scope.orderObj.settleMachineNo = {
                            code: $scope.orderObj.useMachineNo,
                            name: $scope.orderObj.useMachineNo
                        };
                    }
                    // 根据客户名称和使用整机编号，查询机型列表
                    getModelList().then(function () {
                        $scope.orderObj.model = {code: data.model, name: data.model};
                    });
                    // 选择完客户后将零件的价格方案清空
                    angular.forEach($scope.orderObj.detailVOList, function (item) {
                        $scope.clearPriceScheme(item);
                    })
                })
            };

            // 选择完客户后，查询出机型列表
            function getModelList() {
                $scope.modelList = [];
                return getClientInfo({
                    clientName: $scope.orderObj.clientName,
                    carNo: $scope.orderObj.useMachineNo.code
                }).then(function (data) {
                    angular.forEach(data, function (item) {
                        var obj = {name: item.model, code: item.model};
                        $scope.modelList.push(obj);
                    });
                    // 给$scope.modelList去重
                    $scope.modelList = removeDouble($scope.modelList, 'code');
                    return data;
                });
            }


            // 给对象数组去重
            function removeDouble(list, col) {
                var obj = {};
                return list.reduce(function (cur, next) {
                    obj[next[col]] ? "" : obj[next[col]] = true && cur.push(next);
                    return cur;
                }, [])
            }

            // 改变使用整机编号时根据客户名称和选择的整机编号获取机型
            $scope.changeModel = function () {
                // 如果使用整机编号没值则将机型置空
                if (!$scope.orderObj.useMachineNo.code) {
                    $scope.orderObj.model = null;
                    return;
                }
                getModelList().then(function () {
                    $scope.orderObj.model = null;
                })
            };

            // 补录索赔单号
            $scope.addClaimOrder = function (id) {
                if (!$scope.orderObj.addClaimOrderNo) {
                    ybWidget.ShowMessage('索赔单号不能为空！');
                    return;
                }
                var url = '/salesBill/addClaimOrdNo';
                var params = {
                    claimOrderNo: $scope.orderObj.addClaimOrderNo.trim(),
                    id: id
                };
                ybHttp.Get('device', url, params).then(function (res) {
                    if (res.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    $scope.orderObj.claimOrderNo = $scope.orderObj.addClaimOrderNo;
                    ybWidget.ShowToaster('success', '补录成功');
                });
            };

            // 通过客户名称来获取相关客户信息
            function getClientInfo(filters) {
                var service = "device";
                var reqUrl = "/dealerVehicle/notDeactivatedList";
                var param = {};
                param.pageSize = 0;
                param.pageNum = 1;
                param.filters = filters;
                return ybHttp.Post(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return;
                    }
                    return resp.value.list
                });
            }

            // 获取机型编号列表
            function getMachineNoList() {
                var machineNoList = [];
                getClientInfo({keyWord: $scope.orderObj.clientName}).then(function (data) {
                    angular.forEach(data, function (item) {
                        var obj = {
                            name: item.carNo,
                            code: item.carNo,
                            universalLaveAmount: item.universalLaveAmount,
                            maintenanceLaveAmount: item.maintenanceLaveAmount
                        };
                        machineNoList.push(obj);
                    });
                    $scope.machineNoList = removeDouble(machineNoList, 'code');;
                });
            }

            // 选择结算机型后改变剩余额度
            $scope.changeRemainingCredit = function () {
                var settleMachine = angular.copy($scope.orderObj.settleMachineNo);
                $scope.orderObj.universalLaveAmount = settleMachine.universalLaveAmount;
                $scope.orderObj.maintenanceLaveAmount = settleMachine.maintenanceLaveAmount;
                $scope.getRemainingCredit();
            };

            $scope.selectDispatch = function () {

                var param = {
                    name: "调度员",
                    type: "staffByWorkspace",
                    supplierOrgId: $scope.curOrgId
                };
                ybWidget.SingleSelector(param).then(function (data) {
                    $scope.orderObj.headerInfo.dispatcherName = data.name;
                    $scope.orderObj.headerInfo.dispatcherId = data.userId;
                })
            };

            $scope.actionUrl = ybHttp.RequestUrl("device", "/threeGuaranteesPur/download");

            function getBillIds() {
                $scope.exportParam.sectionParam.ids = [];
                angular.forEach($scope.dataList, function (item) {
                    if (!!item.isChecked) {
                        $scope.exportParam.sectionParam.ids.push(item.id);
                    }
                });
            }

            function checkAll(list) {
                var selectAll = false;
                for (var i = 0, len = list.length; i < len; i++) {
                    if (!list[i].isChecked) {
                        selectAll = false;
                        break;
                    }
                    selectAll = true;
                }
                return selectAll;
            }

            $scope.selectSingle = function (item, list, type) {
                if (!item.isChecked) {
                    $scope.markInfo["allChecked" + type] = false;
                } else {
                    if (!checkAll(list)) {
                        $scope.markInfo["allChecked" + type] = false;
                    } else {
                        $scope.markInfo["allChecked" + type] = true;
                    }
                }
                getBillIds();
            };


            $scope.selectAll = function (list, type) {
                angular.forEach(list, function (item) {
                    item.isChecked = $scope.markInfo["allChecked" + type];
                });
                getBillIds();
            };

            // 改变赠送额度类型或者改变客户名称时，获取剩余赠送保养额度
            $scope.getRemainingCredit = function (data) {
                var tempDataObj = data || $scope.orderObj;
                if (!!$scope.orderObj.clientName && !!$scope.orderObj.giveQuotaType) {
                    if (+$scope.orderObj.giveQuotaType === giveQuotaTypeEnum.Ordinary) {
                        $scope.orderObj.remainingCredit = tempDataObj.universalLaveAmount;
                    } else if (+$scope.orderObj.giveQuotaType === giveQuotaTypeEnum.Maintain) {
                        $scope.orderObj.remainingCredit = tempDataObj.maintenanceLaveAmount;
                    }
                }
            };

            $scope.setPrice = function (item, colItem) {
                if (colItem === "applyQty") {
                    setPrice(item, colItem);
                }
            };

            $scope.setAdjustPrice = function (item, colItem) {
                setAdjustPrice(item, colItem)
            };

            function setPrice(item, colItem) {
                item.qtyErr = false;
                if (!item[colItem] || parseFloat(item[colItem]) <= 0) {
                    item.qtyErr = true;
                    return;
                }
                if (item.qty > 99999999.99) {
                    item.qty = 99999999.99;
                }
                item.amountAfterAdjust = item.applyQty;
                if (angular.isUndefined(item[colItem]) || item[colItem] === "") {
                    item.applyTotalPrice = "";
                    item.costSubtotal = 0;
                } else {
                    // 设置零件列表内的申请总价，调整后总价
                    item.applyTotalPrice = $filter("decimalCover")(ybWidget.Times(item.applyQty, item.singlePrice), 2);
                    item.adjustedTotalPrice = $filter("decimalCover")(ybWidget.Times(item.applyQty, item.adjustedSinglePrice), 2);
                    // 设置成本小计
                    item.costSubtotal = $filter("decimalCover")(ybWidget.Times(item.applyQty, item.costPrice), 2);
                }
                setTotalPrice();
                setTotalPriceAdjust();
            }

            // 修改调整后单价
            function setAdjustPrice(item, colItem) {
                item.qtyAdjustErr = false;
                item.priceAdjustErr = false;

                if (item.amountAfterAdjust > 99999999.99) {
                    item.amountAfterAdjust = 99999999.99;
                }
                if (angular.isUndefined(item[colItem]) || item[colItem] === "") {
                    item.adjustedTotalPrice = ""
                } else {
                    item.adjustedTotalPrice = $filter("decimalCover")(ybWidget.Times(item.adjustedSinglePrice, item.applyQty), 2);
                }
                setTotalPriceAdjust();
            }

            // 设置头部信息中的订单总价
            function setTotalPrice() {
                var totalPrice = 0;
                var costTotal = 0;   // 成本总价
                angular.forEach($scope.orderObj.detailVOList, function (item) {
                    totalPrice = ybWidget.Plus(totalPrice, parseFloat(item.applyTotalPrice || 0));
                    costTotal = ybWidget.Plus(costTotal, parseFloat(item.costSubtotal || 0));
                });
                $scope.orderObj.totalOrderPrice = $filter("decimalCover")(totalPrice, 2);
                $scope.orderObj.costTotal = $filter("decimalCover")(costTotal, 2);
            }

            // 设置头部信息中的调整后总价
            function setTotalPriceAdjust() {
                var totalPrice = 0;
                angular.forEach($scope.orderObj.detailVOList, function (item) {
                    if (!item.adjustedTotalPrice && !item.totalPriceAfterAdjust) {
                        return false;
                    }
                    totalPrice = ybWidget.Plus(totalPrice, parseFloat(item.adjustedTotalPrice ? item.adjustedTotalPrice : item.totalPriceAfterAdjust));
                });
                $scope.orderObj.adjustedTotalPrice = $filter("decimalCover")(totalPrice, 2);
            }

            $scope.chosePriceScheme = function (item, index) {
                if (!$scope.orderObj.clientName) {
                    ybWidget.ShowMessage("请先选择客户", MESG_TYPE.Error);
                    return;
                }

                var param = {
                    schemeType: 0,
                    apiObj: {
                        param: {
                            dealerOrgId: $scope.orderObj.clientId,
                            materialsNo: item.materialsNo
                        }
                    }
                };
                ybWidget.PriceSchemeSelector(param).then(function (data) {
                    setPriceScheme(item, index, data);
                })
            };

            function setPriceScheme(item, index, priceScheme) {
                item.priceGroup = priceScheme.name;
                // 固定折扣
                if (priceScheme.modeType === 0) {
                    item.adjustedSinglePrice = priceScheme.discountPrice;

                } else if (priceScheme.modeType === 1) {//指定价格
                    item.adjustedSinglePrice = priceScheme.price;
                }
                item.adjustedTotalPrice = $filter("decimalCover")(ybWidget.Times(item.applyQty, item.adjustedSinglePrice), 2);
                setAdjustPrice(item, "adjustedSinglePrice");
            }

            EventBus.Subscribe("onMaterialChange", setTotal);

            function setTotal() {
                setTotalPrice();
                setTotalPriceAdjust();
            };


            $scope.$on("$destroy", function () {
                EventBus.Unsubscribe("onMaterialChange", setTotal);
            });

            // 通过借用单号来查详情
            function getBorrowDetail(billId) {
                var service = "device";
                var reqUrl = "/serviceBorrowOut/item";
                var param = {};
                param.id = billId;
                return ybHttp.Get(service, reqUrl, param).then(function (resp) {
                    if (resp.code !== 0) {
                        ybWidget.ShowMessage(resp, MESG_TYPE.Error);
                        return false;
                    }
                    $scope.orderObj = resp.value;
                    $scope.orderObj.servicePersonName = resp.value.serviceStaffName;
                    $scope.orderObj.servicePersonId = resp.value.serviceStaffId;
                    $scope.orderObj.workOrderNo = resp.value.dispatchNo;
                    $scope.orderObj.detailVOList = resp.value.serviceBorrowOutDetailVOS;
                    $scope.orderObj.clientName = resp.value.customerName;
                    $scope.orderObj.clientId = resp.value.customerId;
                    // 获取整机编号列表
                    getMachineNoList();
                    // 从服务借用单转销售过来
                    var tempTotalPrice = 0;
                    var detailVOList = $scope.orderObj.detailVOList;
                    for (var i = detailVOList.length - 1; i >= 0; i--) {
                        // 借用出库数量为0的零件都删除
                        if (!detailVOList[i].outQuantity || detailVOList[i].outQuantity <= 0) {
                            detailVOList.splice(i, 1);
                            continue;
                        }
                        detailVOList[i].applyQty = detailVOList[i].canResaleQty;
                        detailVOList[i].applyTotalPrice = $filter("decimalCover")(ybWidget.Times(detailVOList[i].applyQty, detailVOList[i].price), 2);
                        detailVOList[i].adjustedTotalPrice = $filter("decimalCover")(ybWidget.Times(detailVOList[i].applyQty, detailVOList[i].price), 2);
                        tempTotalPrice = ybWidget.Plus(tempTotalPrice, parseFloat(detailVOList[i].applyTotalPrice));
                    }
                    $scope.orderObj.adjustedTotalPrice = tempTotalPrice;
                    $scope.orderObj.totalOrderPrice = tempTotalPrice;
                    $scope.orderObj.borrowBillNo = resp.value.borrowNo;

                    // 新增时默认赠送额度类型为通用
                    $scope.orderObj.giveQuotaType = $scope.giveQuotaTypeEnum.Ordinary;
                    setGiveQuotaType();

                    $scope.tabFlag.type = 1;
                    $scope.tabFlag.name = tabFlag[1];
                    $scope.changeTab(2);
                    return resp.value;
                });
            };


            // 获取客户信息的接口


            // 清除价格方案
            $scope.clearPriceScheme = function (item) {
                item.priceGroup = "";
                item.adjustedSinglePrice = item.price;
                setAdjustPrice(item, "adjustedSinglePrice");
            };

            $scope.salesChannelList = [
                {name: '其他渠道', value: '0'},
                {name: '服务人员渠道', value: '1'},
                {name: '电商渠道', value: '2'},
                {name: '专营店渠道', value: '3'},
                {name: '展会渠道', value: '4'},
                {name: '电话渠道', value: '5'}
            ];

            $scope.selectFactory = function () {
                ybWidget.DataSelector({
                    title: '主机厂',
                    url: `/company/list`,
                    otherParams: { isSap: 1 },
                    fields: [
                        {
                            name: '公司名称',
                            dataField: 'companyName',
                            width: "50%"
                        },
                        {
                            name: '组织机构代码',
                            dataField: 'orgCode',
                            width: "50%"
                        },
                    ],
                }).then(data => {
                    $scope.orderObj.factoryOrgName = data.companyName;
                    $scope.orderObj.factoryOrgId = data.orgId;
                })
            };

            (function () {
                // 从服务借用单跳转过来
                if (!!$stateParams.borrowId) {
                    getBorrowDetail($stateParams.borrowId)
                }
                getDataList();
                $scope.setFixedWidth();
                UserContextService.SetBtnPermission(setBtnPermission);
            })();
        }])
    ;
})(window, window.angular);
